import time
import subprocess
import os
import markdown
from flask import Flask, request, send_from_directory, jsonify
from jinja2 import Environment, PackageLoader, select_autoescape

app = Flask(__name__)

current_dir = os.path.dirname(__file__)
base_dir = os.path.join(current_dir, 'data')
if not os.path.exists(base_dir):
    os.mkdir(base_dir)

MIND_MAPPING_DIR = os.path.join(base_dir, 'mind_mapping')
PPT_DIR = os.path.join(base_dir, 'ppt')
GTT = os.path.join(base_dir, 'gtt')
if not os.path.exists(MIND_MAPPING_DIR):
    os.makedirs(MIND_MAPPING_DIR, exist_ok=True)
if not os.path.exists(PPT_DIR):
    os.makedirs(PPT_DIR, exist_ok=True)
if not os.path.exists(GTT):
    os.makedirs(GTT, exist_ok=True)

# 配置文件夹路径
UPLOAD_FOLDER = os.path.join(base_dir, 'markdown-quiz-files')
OUTPUT_FOLDER = os.path.join(base_dir, 'quiz-data')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024  # 50 MB

# 确保文件夹存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)

server_ip = os.environ.get('server_ip', 'http://0.0.0.0')


@app.route('/mindmap/upload', methods=['POST'])
def upload_markdown_mindmap():
    content = request.get_data(as_text=True)
    time_name = str(int(time.time()))
    file_name = time_name + ".md"
    html_name = time_name + ".html"
    with open(f'{os.path.join(MIND_MAPPING_DIR, file_name)}', 'w', encoding='utf-8') as f:
        f.write(content)
    # 转换md为html
    subprocess.run(
        ['npx', 'markmap-cli', f'{os.path.join(MIND_MAPPING_DIR, file_name)}', '--no-open'],
        capture_output=True,
        text=True)
    return f'Markdown 文件已保存\n预览链接: {server_ip}:5003/mindmap/html/{html_name}'


@app.route('/mindmap/html/<filename>', methods=['GET'])
def get_html_mindmap(filename):
    return send_from_directory(MIND_MAPPING_DIR, filename)


@app.route('/ppt/upload', methods=['POST'])
def upload_markdown_ppt():
    content = request.get_data(as_text=True)
    file_name = str(int(time.time())) + ".md"
    with open(f"{os.path.join(PPT_DIR, file_name)}", 'w', encoding='utf-8') as f:
        f.write(content)
    return f'Markdown 文件已保存\n预览链接: {server_ip}:5003/{file_name} \n下载链接: {server_ip}:5003/{file_name}?pptx'


@app.route('/gtt/upload', methods=['POST'])
def upload_markdown_gtt():
    content = request.get_data(as_text=True)
    time_name = str(int(time.time()))
    file_name = time_name + ".md"
    # 防止格式不对
    if '```mermaid' not in content:
        content = '```mermaid\n' + content + '\n```'
    with open(f"{os.path.join(GTT, file_name)}", 'w', encoding='utf-8') as f:
        f.write(content)
    subprocess.run([
        'mmdc', '-p', 'puppeteer-config.json', '-c', 'config.json', '-i',
        f'./data/gtt/{file_name}'
    ])
    return f'Markdown 文件已保存\n预览链接: {server_ip}:5003/gtt/svg/{file_name}-1.svg'


@app.route('/gtt/svg/<filename>', methods=['GET'])
def get_svg(filename):
    return send_from_directory(f'{GTT}', filename)


@app.route('/quiz/upload_markdown', methods=['POST'])
def upload_markdown_quiz():
    content = request.get_data(as_text=True)
    print(content)
    if content is None:
        return jsonify({"error": "Invalid input"}), 400
    """Render quiz in Markdown format to HTML."""
    extensions = [
        "tables", "app.extensions.checkbox", "app.extensions.radio",
        "app.extensions.textbox"
    ]
    html = markdown.markdown(content, extensions=extensions, output_format="html5")
    env = Environment(loader=PackageLoader('app', 'static'), autoescape=select_autoescape(['html', 'xml']))
    javascript = env.get_template('app.js').render()
    test_html = env.get_template('base.html').render(content=html, javascript=javascript)
    test_html = env.get_template('wrapper.html').render(content=test_html)
    filename = str(int(time.time()))
    with open(os.path.join(OUTPUT_FOLDER, f"{filename}.html"), "w+", encoding='utf-8') as f:  # create final file
        f.write(test_html)
    return jsonify(
        {"message":
         f"保存成功\n查看链接 {server_ip}:5003/quiz/get_html/{filename}"}), 200


@app.route('/quiz/get_html/<filename>', methods=['GET'])
def get_html(filename):
    if not filename.endswith('.html'):
        filename += '.html'

    file_path = os.path.join(OUTPUT_FOLDER, filename)
    if not os.path.exists(file_path):
        return jsonify({"error": "File not found"}), 404
    return send_from_directory(OUTPUT_FOLDER, filename)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5003)
